package com.lanou.service.impl;

import com.lanou.bean.Blog;
import com.lanou.mapper.BlogMapper;
import com.lanou.mapper.LuceneDao;
import com.lanou.service.BlogService;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

/**
 * Created by dllo on 18/2/27.
 */
@Service
public class BlogServiceImpl implements BlogService {

    @Resource
    private BlogMapper blogMapper;
    @Resource
    private LuceneDao luceneDao;


    @Override
    public void addBlog(@Param(value = "title") String title,
                        @Param(value = "desc") String desc,
                        @Param(value = "content") String content,
                        @Param(value = "userId") int userId) {
        int a = blogMapper.addBlog(title, desc, content, userId);
        System.out.println(a);
        //如果添加成功就添加索引
        if (a == 1) {
            Blog blog = new Blog(title, desc, content, userId);
            try {
                luceneDao.addIndex(blog);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public List<Blog> searchAllBlog() {
        return blogMapper.searchAllBlog();
    }

    @Override
    public void deleteBlog(@Param(value = "bid") int bid) {
        int i = blogMapper.deleteBlog(bid);
//        if (i == 1) {
//            luceneDao.delIndex();
//        }
    }

    @Override
    public Blog seeMore(@Param(value = "bid") int bid) {
        return blogMapper.seeMore(bid);
    }

    //分页
    @Override
    public int page() {
        List<Blog> list = blogMapper.searchAllBlog();
        int count = list.size();
        int num = (int) Math.ceil(count / 3.0);
        return num;
    }

    @Override
    public List<Blog> clickPage(@Param(value = "page") int page) {
        return blogMapper.limitSerch((page - 1) * 3);
    }

    @Override
    public List<Blog> searchByKeyWord(@Param(value = "keyword") String keyWord) {
//        return blogMapper.SearchByKeyWord(keyWord);
        List<Blog> blogList = null;
        try {
            blogList = luceneDao.findIndex(keyWord, 0, 3);
            System.out.println(blogList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return blogList;
    }


}
